﻿/*-----------------------------------------------------------------------------------------------
// Copyright (C) yangrongfeng 
//
// 文件名：         BaseController.cs
// 文件功能描述：   控制器基类
//
// 
// 创建标识：       杨荣峰  2016-04-21
//
// 修改标识：
// 修改描述：
//
// 备注：	
// 				
//-----------------------------------------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Mvc;
using HYBY.WebFrameWork.Security;
using HYBY.WebFrameWork.Mvc;
/*命名空间位置说明：
 * 系统命名空间放第一位；
 * 解决方案内部引用放第二位；
 * 解决方案外部，系统内部引用放在第三位；
 * 第三方开源组件放第四位；
 * 第三方商业组件放第五位
 */

namespace HYBY.WebFrameWork.Controllers
{
    /// <summary>
    /// 控制器基类
    /// </summary>
    public abstract class BaseController : Controller {

        #region 消息提示

        /// <summary>
        /// 提示信息视图
        /// </summary>
        /// <param name="message">提示信息</param>
        /// <returns></returns>
        protected ViewResult PromptView(string message)
        {
            return View("prompt", new PromptModel(message));
        }

        /// <summary>
        /// 提示信息视图
        /// </summary>
        /// <param name="backUrl">返回地址</param>
        /// <param name="message">提示信息</param>
        /// <returns></returns>
        protected ViewResult PromptView(string backUrl, string message)
        {
            return View("prompt", new PromptModel(backUrl, message));
        }

        /// <summary>
        /// ajax请求结果
        /// </summary>
        /// <param name="state">状态</param>
        /// <param name="content">内容</param>
        /// <returns></returns>
        protected ActionResult AjaxResult(string state, string content)
        {
            return AjaxResult(state, content, false);
        }

        /// <summary>
        /// ajax请求结果
        /// </summary>
        /// <param name="state">状态</param>
        /// <param name="content">内容</param>
        /// <param name="isObject">是否为对象</param>
        /// <returns></returns>
        protected ActionResult AjaxResult(string state, string content, bool isObject)
        {
            return Content(string.Format("{0}\"state\":\"{1}\",\"content\":{2}{3}{4}{5}", "{", state, isObject ? "" : "\"", content, isObject ? "" : "\"", "}"));
        }

        #endregion

        /// <summary>
        /// 将视图(View)或者分部视图(PartialView)生成为字符串
        /// </summary>
        /// <returns>结果</returns>
        public virtual string RenderPartialViewToString()
        {
            return RenderPartialViewToString(null, null);
        }
        /// <summary>
        /// 将分部视图(PartialView)生成为字符串
        /// </summary>
        /// <param name="viewName">View name</param>
        /// <returns>结果</returns>
        public virtual string RenderPartialViewToString(string viewName)
        {
            return RenderPartialViewToString(viewName, null);
        }
        /// <summary>
        /// 将分部视图(PartialView)生成为字符串
        /// </summary>
        /// <param name="model">实体模型对象</param>
        /// <returns>结果</returns>
        public virtual string RenderPartialViewToString(object model)
        {
            return RenderPartialViewToString(null, model);
        }
        /// <summary>
        ///  将分部视图(PartialView)生成为字符串
        /// </summary>
        /// <param name="viewName">视图名称</param>
        /// <param name="model">实体模型对象</param>
        /// <returns>结果</returns>
        public virtual string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = this.ControllerContext.RouteData.GetRequiredString("action");

            this.ViewData.Model = model;

            using (var sw = new StringWriter())
            {
                ViewEngineResult viewResult = System.Web.Mvc.ViewEngines.Engines.FindPartialView(this.ControllerContext, viewName);
                var viewContext = new ViewContext(this.ControllerContext, viewResult.View, this.ViewData, this.TempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
        }


        public AuthUser CurrentUser {
      get {
        if (HttpContext.User.Identity == null)
          Response.Redirect("Account/Login");
        return HttpContext.User.Identity as AuthUser;
      }
    }

    /// <summary>
    /// On exception
    /// </summary>
    /// <param name="filterContext">Filter context</param>
    protected override void OnException(ExceptionContext filterContext) {
      if (filterContext.Exception != null)
        LogException(filterContext.Exception);
      base.OnException(filterContext);
    }

    /// <summary>
    /// Log exception
    /// </summary>
    /// <param name="exc">Exception</param>
    protected void LogException(Exception exc) {
      ErrorModel model = new ErrorModel();
      model.Source = exc.Source;
      model.Message = exc.Message;
    }

    /// <summary>
    /// Display success notification
    /// </summary>
    /// <param name="message">Message</param>
    /// <param name="persistForTheNextRequest">A value indicating whether a message should be persisted for the next request</param>
    protected virtual void SuccessNotification(string message, bool persistForTheNextRequest = true) {
      AddNotification(NotifyType.Success, message, persistForTheNextRequest);
    }
    /// <summary>
    /// Display error notification
    /// </summary>
    /// <param name="message">Message</param>
    /// <param name="persistForTheNextRequest">A value indicating whether a message should be persisted for the next request</param>
    protected virtual void ErrorNotification(string message, bool persistForTheNextRequest = true) {
      AddNotification(NotifyType.Error, message, persistForTheNextRequest);
    }
    /// <summary>
    /// Display error notification
    /// </summary>
    /// <param name="exception">Exception</param>
    /// <param name="persistForTheNextRequest">A value indicating whether a message should be persisted for the next request</param>
    /// <param name="logException">A value indicating whether exception should be logged</param>
    protected virtual void ErrorNotification(Exception exception, bool persistForTheNextRequest = true, bool logException = true) {
      if (logException)
        AddNotification(NotifyType.Error, exception.Message, persistForTheNextRequest);
    }

    /// <summary>
    /// Display notification
    /// </summary>
    /// <param name="type">Notification type</param>
    /// <param name="message">Message</param>
    /// <param name="persistForTheNextRequest">A value indicating whether a message should be persisted for the next request</param>
    protected virtual void AddNotification(NotifyType type, string message, bool persistForTheNextRequest) {
      string dataKey = string.Format("tp.notifications.{0}", type);
      if (persistForTheNextRequest) {
        if (TempData[dataKey] == null)
          TempData[dataKey] = new List<string>();
        ((List<string>)TempData[dataKey]).Add(message);
      }
      else {
        if (ViewData[dataKey] == null)
          ViewData[dataKey] = new List<string>();
        ((List<string>)ViewData[dataKey]).Add(message);
      }
    }

    protected virtual void ActiveMenu(string activeId) {
      string dataKey = "tp.activeMenu";

      if (System.Web.HttpContext.Current.Session[dataKey] == null) {
        System.Web.HttpContext.Current.Session.Add(dataKey, activeId);
      }
      else {

        System.Web.HttpContext.Current.Session[dataKey] = activeId;
      }

    }

    protected virtual void ActiveNavigation(string activeId) {
      string dataKey = "tp.activeMenu";
      if (ViewData[dataKey] == null) {
        ViewData.Add(dataKey, activeId);
      }
      else {
        ViewData[dataKey] = activeId;
      }
    }
  }
}